import Foundation
import UIKit
import SnapKit
import Alamofire

class TopBarGVView: UIView{
    //全局变量
    private var img:UIImageView = UIImageView()
    private var label:UILabel={
        let uiLabel = UILabel()
        uiLabel.textColor = .white
        uiLabel.adjustsFontSizeToFitWidth = true
        uiLabel.minimumScaleFactor = 0.25
        return uiLabel
    }()
    private var button:UIButton=UIButton()
    private let api = "/growthvalue/topbar"
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        loadData(userId: 1)
        
    }
    required init?(coder: NSCoder) {
        fatalError("init(coder:NSCoder) -- fatalError")
    }
    func setupUI(){
        self.backgroundColor = .black
        self.label.attributedText = ColorTool.setColorForPartText(start: 8, length: 10, targetText: label.text!, color: .green)
        self.button.tintColor = .white
        
        self.addSubview(label)
        self.addSubview(img)
        self.addSubview(button)
        
        img.snp.makeConstraints { make in
            make.width.height.equalTo(18)
            make.centerY.equalToSuperview()
            make.left.equalToSuperview().inset(12)
        }
        label.snp.makeConstraints { make in
            make.width.equalTo(272)
            make.height.equalTo(16)
            make.centerY.equalToSuperview()
            make.left.equalToSuperview().inset(36)
        }
        button.snp.makeConstraints { make in
            make.width.equalTo(10)
            make.height.equalTo(8)
            make.centerY.equalToSuperview()
            make.left.equalTo(label.snp.right).inset(0)
        }
    }
    func loadData(userId:Int){
        
        
        let url = AllUrl.LH_URL + api + "?userId=\(userId)"
        
        AF.request(url,method: .get)
            .validate(statusCode: 200..<300)
            .responseDecodable(of:TopBarGBInfo.self){ response in
                switch response.result{
                case .success(let header):
                    DispatchQueue.main.async {
                        self.label.text = "剩余解锁次数将于" + header.textLabel + "清零，请及时使用"
                        self.img.image = UIImage(named: header.imgPath)
                        self.button.setImage(UIImage(systemName: header.btnImg), for: .normal)
                        self.setupUI()
                    }
                case .failure(let error):
                    print("错误 -- topBarGV: \(error.localizedDescription)")
                }
            }
    }
}

